<template>
  <div class="user-manage-container">
    <el-card class="header">
      <div class="search-container">
        <el-form
          :inline="true"
          size="default"
          label-position="left"
          :model="serarchForm"
          ref="searchFormRef"
        >
<!--          <el-form-item-->
<!--            label="姓名:"-->
<!--            prop="username">-->
<!--            <el-input type="text" name="username"  placeholder="请输入姓名" v-model="serarchForm.username"/>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="联系方式:" prop="telephone">-->
<!--            <el-input type="text" name="telephone"   placeholder="请输入联系方式" v-model="serarchForm.telephone"/>-->
<!--          </el-form-item>-->
          <el-form-item>
            <el-button type="primary" size="default" @click="searchClick" >
              <el-icon>
                <component :is="`el-icon-${toLine('Search')}`" />
              </el-icon>
              <span>搜索</span>
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button size="default" @click="resetClick(searchFormRef)">
              <span>重置</span>
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="tools" style="display: flex">
        <el-button type="primary" size="default" @click="onLineDraw">
          <el-icon>
            <el-icon-edit></el-icon-edit>
          </el-icon>
          <span>绘制流程图</span>
        </el-button>
        <el-upload :before-upload="beforeUpload" style="margin-left: 10px;" size="default"
                   :show-file-list="false"
                   ref="uploadForm"
                   :http-request="uploadFile"
                   :limit="1"
                   accept="application/bpmn20-xml"
                   action="string"
                   multiple>
          <el-button type="primary">
            <el-icon>
              <component :is="`el-icon-${toLine('UploadFilled')}`"></component>
            </el-icon>
            上传并部署
          </el-button>
        </el-upload>
<!--        <el-button type="primary" size="default" v-permission="['user.add']" @click="addUser">-->
<!--          <el-icon>-->
<!--            <el-icon-plus></el-icon-plus>-->
<!--          </el-icon>-->
<!--          <span>添加用户</span>-->
<!--        </el-button>-->
<!--        <el-button type="primary" v-permission="['user.excelImport']" @click="onImportExcelClick">-->
<!--          <el-icon>-->
<!--            <el-icon-uploadfilled></el-icon-uploadfilled>-->
<!--          </el-icon>-->
<!--          <span>{{$t('msg.excel.importExcel')}}</span>-->
<!--        </el-button>-->
<!--        <el-button type="success" v-permission="['user.excelExport']" @click="onToExcelClick">-->
<!--          <el-icon>-->
<!--            <el-icon-download></el-icon-download>-->
<!--          </el-icon>-->
<!--          <span>{{$t('msg.excel.exportExcel')}}</span>-->
<!--        </el-button>-->
      </div>
    </el-card>
    <!--  table  -->
    <el-card>
      <el-table :data="tableData" border style="width: 100%">
        <!--    索引    -->
        <el-table-column label="#" type="index"></el-table-column>
        <!--    姓名    -->
        <el-table-column
          prop="id"
          label="id">
        </el-table-column>
        <el-table-column
          prop="name"
          label="名称">
        </el-table-column>
        <el-table-column
          prop="processDefinitionName"
          label="流程定义名称">
        </el-table-column>
        <el-table-column
          prop="processDefinitionKey"
          label="流程定义Key">
        </el-table-column>
        <el-table-column
          prop="resourceName"
          label="resourceName">
        </el-table-column>
        <el-table-column
          prop="version"
          label="版本">
        </el-table-column>
        <el-table-column
          prop="key"
          label="key">
        </el-table-column>
        <!--    手机号    -->
        <el-table-column
          prop="deploymentTime"
          label="部署时间">
        </el-table-column>
        <!--    操作    -->
        <el-table-column label="操作" fixed="right" width="300">
          <template #default="{ row }">
            <el-button type="primary" size="default" @click="onStartClick(row)">
              <el-icon>
                <component :is="`el-icon-${toLine('Setting')}`" />
              </el-icon>
              <span>启动</span>
            </el-button>
            <el-button type="warning" size="default" @click="onShowClick(row)">
              <el-icon>
                <component :is="`el-icon-${toLine('View')}`" />
              </el-icon>
              <span>预览</span>
            </el-button>
            <el-button type="danger" size="default" v-permission="['user.delete']" @click="onRemoveClick(row.id)">
              <el-icon>
                <component :is="`el-icon-${toLine('Delete')}`" />
              </el-icon>
              <span>删除</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[5,10,15,20]"
        layout="total,sizes,prev,pager,next,jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch, onActivated } from 'vue'
import { processDefinitionDelete, processDeploymentList, processInstanceStart, uploadStreamAndDeployment } from '../../../../api/process'
import { watchSwitchLang } from '../../../../utils/i18n'
import { useRouter } from 'vue-router'
import { FormInstance } from "element-plus";
import { toLine } from '../../../../utils/index'
const router = useRouter()
// 数据相关对象
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const serarchForm = reactive({
  username: '',
  telephone: ''
})
/**
 * 获取数据的方法
 */
const getListData = async () => {
  // console.log(serarchForm)
  if (serarchForm.username !== '' || serarchForm.telephone !== '') {
    const payLoad = {
      condition: serarchForm,
      page: {
        currentPage: currentPage.value,
        pageSize: pageSize.value
      }
    }
    const result = await processDeploymentList(payLoad)
    tableData.value = result.list
    total.value = result.total
  } else {
    const payLoad = {
      page: {
        currentPage: currentPage.value,
        pageSize: pageSize.value
      }
    }
    const result = await processDeploymentList(payLoad)
    tableData.value = result.list
    total.value = result.total
  }
}
watchSwitchLang(getListData())
const handleSizeChange = (size: number) => {
  pageSize.value = size
  getListData()
}
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  getListData()
}
// 搜索
const searchClick = () => {
  getListData()
}
const searchFormRef = ref<FormInstance>()
const resetClick = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
// 上传文件之前
const beforeUpload = (file: any) => {
  // const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
  // const extension1 = fileSuffix === "png";
  // const extension2 = fileSuffix === "jpg";
  // const extension3 = fileSuffix === "jpeg";
  // const isLt2M = file.size / 1024 / 1024 < 0.5;
  // if (!extension1 && !extension2 && !extension3) {
  //   // this.$msg("上传文件只能是 png、jpg、jpeg格式", "error");
  //   return false;
  // }
  //
  // if (!isLt2M) {
  //   // this.$msg("上传文件大小不能超过 2MB", "error");
  //   return false;
  // }
}
// 上传文件
const uploadFile= (item: any) => {
  // 开始上传文件 新建一个formData
  const formData = new FormData();
  // 通过append向form对象添加数据
  formData.append("file", item.file);
  uploadStreamAndDeployment(formData)
    .then(async (e) => {
      console.log("上传成功");
      await getListData()
    })
    .catch((e) => {
      console.log("上传失败");
      // clearFlies();
    });
}
const onLineDraw = () => {
  router.push('/process/design')
}

// 移除上传图片列表
// const clearFlies = () => {
//   uploadForm.clearFiles();
// }
// 启动流程实例
const onStartClick = async (row: any) => {
  const data = {
    'instanceName': 'webView测试启动流程实例',
    'processDefinitionKey': row.processDefinitionKey
  }
  await processInstanceStart(data)
  await getListData()
}
// 为用户分配角色
const rolesDialogVisible = ref(false)
const selectUserId = ref('')
const onShowClick = (row: any) => {
  router.push(`/process/activiti/info/${row.id}`)
}
const onRemoveClick = async (deploymentId: string) => {
  const data = {
    'deploymentId': deploymentId,
  }
  await processDefinitionDelete(data)
  await getListData()
}

// 保证每次打开dialog 都能重新获取数据
watch(rolesDialogVisible, value => {
  if (!value) selectUserId.value = ''
})
// 用户导出
const exportToExcelVisible = ref(false)
const onToExcelClick = () => {
  console.log('onToExcelClick')
  exportToExcelVisible.value = true
}
// 导入
const onImportExcelClick = () => {
  router.push('/user/import')
}

// 处理导入用户后数据不重新加载的问题
onActivated(getListData)
</script>
<style lang="scss" scoped>
.user-manage-container {
  .header {
    margin-bottom: 22px;
    //text-align: right;
    .search-container {
      float: left;
    }
    .tools {
      float: right;
    }
  }
  :deep(.avatar) {
    width: 20px;
    height: 20px;
    border-radius: 2%;
  }
  :deep(.el-tag) {
    margin-right: 6px;
  }
}
.pagination {
  margin-top: 20px;
  text-align: center;
}
</style>
